package com.example.bluetoothnmeatest;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.RTKSDK.BluetoothNMEASDK;
import com.example.RTKSDK.LocationData;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements
        BluetoothNMEASDK.SDKCallback,
        DeviceListAdapter.OnDeviceClickListener {

    private BluetoothNMEASDK bluetoothSDK;
    private DeviceListAdapter deviceListAdapter;
    private Button btnScan, btnDisconnect;
    private TextView tvStatus, tvLatitude, tvLongitude, tvAltitude, tvQuality;
    private RecyclerView rvDevices;

    private boolean isScanning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化UI组件
        btnScan = findViewById(R.id.btnScan);
        btnDisconnect = findViewById(R.id.btnDisconnect);
        tvStatus = findViewById(R.id.tvStatus);
        tvLatitude = findViewById(R.id.tvLatitude);
        tvLongitude = findViewById(R.id.tvLongitude);
        tvAltitude = findViewById(R.id.tvAltitude);
        tvQuality = findViewById(R.id.tvQuality);
        rvDevices = findViewById(R.id.rvDevices);


        // 初始化设备列表
        deviceListAdapter = new DeviceListAdapter();
        deviceListAdapter.setOnDeviceClickListener(this);
        rvDevices.setLayoutManager(new LinearLayoutManager(this));
        rvDevices.setAdapter(deviceListAdapter);

        // 初始化蓝牙SDK
        bluetoothSDK = new BluetoothNMEASDK(this, this);

        // 设置按钮点击监听
        btnScan.setOnClickListener(v -> toggleScan());
        btnDisconnect.setOnClickListener(v -> disconnectDevice());
    }

    private void toggleScan() {
        if (isScanning) {
            stopScan();
            btnScan.setText(R.string.scan_devices);
        } else {
            startScan();
            btnScan.setText(R.string.stop_scan);
        }
        isScanning = !isScanning;
    }

    private void startScan() {
        deviceListAdapter.clearDevices();
        if (bluetoothSDK.checkPermissions()) {
            bluetoothSDK.startDiscovery();
        }
    }

    private void stopScan() {
        // SDK内部已处理停止扫描逻辑
    }

    private void connectDevice(BluetoothDevice device) {
        tvStatus.setText(R.string.connecting);
        bluetoothSDK.connectToDevice(device);
        btnDisconnect.setEnabled(true);
    }

    private void disconnectDevice() {
        bluetoothSDK.disconnect();
        btnDisconnect.setEnabled(false);
        tvStatus.setText(R.string.disconnected);
    }

    @Override
    public void onPermissionRequired(String[] permissions) {
        ActivityCompat.requestPermissions(this, permissions, 101);
    }

    @Override
    public void onDeviceFound(BluetoothDevice device) {
        runOnUiThread(() -> deviceListAdapter.addDevice(device));
    }

    @Override
    public void onDiscoveryFinished() {
        runOnUiThread(() -> {
            Toast.makeText(this, "扫描完成", Toast.LENGTH_SHORT).show();
            btnScan.setText(R.string.scan_devices);
            isScanning = false;
        });
    }

    @Override
    public void onConnected() {
        runOnUiThread(() -> {
            tvStatus.setText(R.string.connected);
            Toast.makeText(this, "设备已连接", Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onDataReceived(LocationData data) {
        runOnUiThread(() -> {
            tvLatitude.setText(String.format(Locale.getDefault(),
                    "纬度: %.8f", data.latitude));
            tvLongitude.setText(String.format(Locale.getDefault(),
                    "经度: %.8f", data.longitude));
            tvAltitude.setText(String.format(Locale.getDefault(),
                    "海拔: %.2f 米", data.altitude));
            String dataQuality = "";
//             0=不可用(FIX NOT valid)，
//             1=单点定位(GPS FIX)，
//             2=差分定位(DGPS)，
//             3=无效PPS，
//             4=固定解（RTK FIX），
//             5=浮点解（RTK FLOAT），
//             6=正在估算
            switch (data.fixQuality) {
                case 0:
                    dataQuality = "不可用";
                    break;
                case 1:
                    dataQuality = "单点定位";
                    break;
                case 2:
                    dataQuality = "差分定位";
                    break;
                case 3:
                    dataQuality = "无效PPS";
                    break;
                case 4:
                    dataQuality = "固定解";
                    break;
                case 5:
                    dataQuality = "浮点解";
                    break;
                case 6:
                    dataQuality = "正在估算";
                    break;
                default:
                    dataQuality = "数据获取失败";
            }
            tvQuality.setText(String.format(Locale.getDefault(),
                    "定位数据质量: %s", dataQuality));
        });
    }

    @Override
    public void onDisconnected() {
        runOnUiThread(() -> {
            tvStatus.setText(R.string.disconnected);
            Toast.makeText(this, "设备已断开", Toast.LENGTH_SHORT).show();
            btnDisconnect.setEnabled(false);
        });
    }

    @Override
    public void onError(String message) {
        runOnUiThread(() -> {
            Toast.makeText(this, "错误: " + message, Toast.LENGTH_LONG).show();
            tvStatus.setText("错误: " + message);
        });
    }

    @Override
    public void onDeviceClick(BluetoothDevice device) {
        connectDevice(device);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bluetoothSDK.disconnect();
    }
}